package ute.mvc.controller.home;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import ute.mvc.model.MyFile;
import ute.mvc.service.FileService;
import ute.mvc.util.FileUtil;

@Controller
@RequestMapping (value = "/file")
public class DownloadController {
	@Autowired
	FileService fileService;
	@Autowired
	ApplicationContext applicationContext;
	@RequestMapping (value ="/{fileId}")
	public void downloadFile(@PathVariable int fileId, HttpServletRequest request, HttpServletResponse response) {
		ServletContext context = request.getServletContext();
		System.out.println("download file");
		
		MyFile myFile = fileService.getFileByFileId(fileId);
		String fullPath = FileUtil.getFileLocation(applicationContext) + "\\" + fileId;
		File downloadFile = new File(fullPath);
		try {
			FileInputStream inputStream = new FileInputStream(downloadFile);
			String mimeType = context.getMimeType(fullPath);
			if (mimeType == null) {
				// set to binary type if MIME mapping not found
				mimeType = "application/octet-stream";
			}
			System.out.println("MIME type: " + mimeType);
			 
	        // set content attributes for the response
	        response.setContentType(mimeType);
	        response.setContentLength((int) downloadFile.length());
	 
	        // set headers for the response
	        String headerKey = "Content-Disposition";
	        String headerValue = String.format("attachment; filename=\"%s\"",
	                myFile.getFileName());
	        response.setHeader(headerKey, headerValue);
	 
	        // get output stream of the response
	        OutputStream outStream = response.getOutputStream();
	 
	        byte[] buffer = new byte[4096];
	        int bytesRead = -1;
	 
	        // write bytes read from the input stream into the output stream
	        while ((bytesRead = inputStream.read(buffer)) != -1) {
	            outStream.write(buffer, 0, bytesRead);
	        }
	 
	        inputStream.close();
	        outStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
